#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
int main()
{
    int pipe_fd[2] = {0};
    if(pipe(pipe_fd) < 0)
    {
        perror("pipe:");
        exit(1);
    }
    //以子进程写 父进程读取为例子
    int id = fork();
    if(id < 0)
    {
        perror("fork :");
        exit(2);
    }
    else if(id == 0)
    {
        //child
        close(pipe_fd[0]);
        const char* msg = "hello Mango";
        int count = 5;
        while(count--)
        {
            write(pipe_fd[1],msg,strlen(msg));
            sleep(1);
        }
        close(pipe_fd[1]);
        printf("child running over!~~~~~\n");
        exit(0);
    }
    //parent
    close(pipe_fd[1]);
    char buffer[64];
    while(1)
    {
        memset(buffer,0,sizeof(buffer));
        ssize_t n = read(pipe_fd[0],buffer,sizeof(buffer)-1);
        if(n == 0)
        {
            printf("对端关闭！读取结束\n");
            break;
        }
        else if(n < 0)
        {
            perror("read:");
            break;
        }
        else
        {
            buffer[n] = 0;
            printf("%s\n",buffer);
        }
    }
    close(pipe_fd[0]);
    return 0; 
}